<template>
	<view class="content">
		<!-- 嘿文标题 -->
		<view class="input-title-view shadow-light fadeIn-1s">
			<u--input class="input-title" border="none" maxlength="20"
				v-model="title" placeholder="嘿文标题 (20字)" :clearable="true">
			</u--input>
		</view>
		<!-- 嘿文内容 -->
		<view class="input-content-view shadow-light fadeIn-1s">
			<u--textarea class="input-content" v-model="content" maxlength="400"
				height="100" placeholder="分享生活点滴~ (必填, 400字)" border="none" 
				:autoHeight="contentAutoHeight" @linechange="onContentLineChange">
			</u--textarea>
		</view>
		<!-- 嘿文图片 -->
		<view class="images-view shadow-light fadeIn-1s">
			<view class="mimages-viwe" v-for="(image, i) in imagePaths" >
				<image class="mimage" :src="image.path" mode="aspectFill" @tap="onImageTap(i)"></image>
				<!-- 删除按钮在图片只有一个的时候取消显示，因为最少要有一张图片 -->
				<view class="iconfont mimage-del" v-if="imagePaths.length > 1"
					@tap="onImageDelTap(i)">&#xe75e;
				</view>
			</view>
			<view class="image-add-view" v-if="imagePaths.length < 9" @tap="onImageAddTap">
				<text class="iconfont image-add">&#xe8a1;</text>
			</view>
		</view>
		<button class="button shadow-light fadeIn-1s" @tap="onSubmitTap">发布</button>
	</view>
</template>

<script>
	import {
		getHeiById,
		deleteHeiImage,
		updateHei
	} from "@/network/HeiApi.js";
	export default {
		data() {
			return {
				imagePaths: [],
				
				title: "",
				content: "",
				
				// 嘿文内容框是否开启自动高度
				contentAutoHeight: false,
				
				// 标记当前是否正在上传
				uploading: false,
				
				// 标记当前是编辑模式还是添加模式
				mode: "add",
				
				// 编辑模式下用来存储嘿文 ID
				heiId: "",
				
				// 编辑模式下存储嘿文数据
				hei: [],
			}
		},
		
		onLoad(options) {
			this.mode = (options.mode == undefined ? "add" : options.mode);
			if (options.mode == "edit") {
				// 当前是编辑模式
				this.heiId = options.heiId;
				uni.setNavigationBarTitle({
					title: "编辑嘿文"
				});
				// 获取嘿文数据
				this.refreshData();
			} else {
				// 当前是新增模式，读取上个页面传过来的嘿文图片地址
				this.imagePaths = JSON.parse(decodeURIComponent(options.files));
			}
		},
		
		/**
		 * 返回事件
		 */
		onBackPress(options) {
			// 正在上传时禁止返回
			if (this.uploading) {
				return true;
			}
			return false;
		},
		
		methods: {
			/**
			 * 编辑嘿文模式下根据嘿文 ID 获取嘿文
			 */
			refreshData: function() {
				getHeiById(this.heiId).then(data => {
					this.hei = data.content;
					this.title = this.hei.title;
					this.content = this.hei.content;
					
					this.imagePaths = [];
					// 格式化嘿文图片数据加入 imagePaths 变量
					for (let i = 0; i < this.hei.images.length; i++) {
						let image = this.hei.images[i];
						let json = {"path": image.src, "heiImageId": image.heiImageId};
						this.imagePaths.push(json);
					}
				}).catch(err => {
					uni.showModal({
						title: "获取嘿文失败",
						content: err
					});
				});
			},
			
			/**
			 * 发布按钮单击事件
			 */
			onSubmitTap: function() {
				let that = this;
				let title = this.title;
				let content = this.content;
				if (content.length == 0) {
					this.toast("请填写嘿文内容");
					return;
				}
				
				if (title.length == 0) {
					// 没填写标题，就取文中前 20 个字
					if (content.length >= 20) {
						title = content.substring(0, 20);
					} else {
						title = content.substring(0, content.length);
					}
				}
				
				
				this.uploading = true;
				uni.showLoading({
					title: "正在上传图片",
					mask: true
				});
				
				let files = new Array();
				if (this.mode == "add") {
					// 新增模式
					for (let i = 0; i < this.imagePaths.length; i++) {
						let obj = new Object();
						obj.name = "file" + i;
						obj.uri = this.imagePaths[i].path;
						files.push(obj);
					}
				} else {
					// 编辑模式
					for (let i = 0; i < this.imagePaths.length; i++) {
						let imagePath = this.imagePaths[i];
						// 只上传没有 heiImageId 字段的图片（编辑模式下新增的图片）
						if (imagePath.heiImageId == undefined || imagePath.heiImageId.length > 0) {
							let obj = new Object();
							obj.name = "file" + i;
							obj.uri = imagePath.path;
							files.push(obj);
						}
					}
				}
				
				
				if (files.length == 0 && this.mode == "edit") {
					// 当没有选择新图片时使用普通网络请求（仅在编辑模式下）
					updateHei(title, content, this.heiId).then(data => {
						uni.hideLoading();
						that.toast("发布成功");
						that.uploading = false;
						uni.navigateBack();
					}).catch(err => {
						uni.hideLoading();
						uni.showModal({
							title: "发布失败",
							content: e.errMsg
						});
						that.uploading = false;
					});
				} else {
					// 有新上传的图片时使用上传文件的请求
					let url = (this.mode == "add") ? "add" : "update";
					uni.uploadFile({
						url: this.getUrl() + "/hei/" + url,
						files: files,
						header: {
							"admin-token": this.getLoginToken()
						},
						formData: {
							"email": this.getData("email"),
							"title": title,
							"content": content,
							"heiId": this.heiId,
							// 标记本次请求是否有新图像
							"haveImage": files.length > 0
						},
						success: function(res) {
							uni.hideLoading();
							that.toast("发布成功");
							that.uploading = false;
							uni.navigateBack();
						},
						fail: function(e) {
							uni.hideLoading();
							uni.showModal({
								title: "发布失败",
								content: e.errMsg
							});
							that.uploading = false;
						}
					});
				}
			},
			
			/**
			 * 添加图片点击事件
			 */
			onImageAddTap: function() {
				let that = this;
				uni.chooseImage({
					sizeType: ["compressed"],
					count: 9 - this.imagePaths.length,
					success:function(res){
						let files = res.tempFiles;
						for (let i = 0; i< files.length; i++) {
							let json = {"path": files[i].path, "size": files[i].size};
							that.imagePaths.push(json);
						}
					}
				});
			},
			
			/**
			 * 图片点击事件，预览图片
			 * @param {Object} i
			 */
			onImageTap: function(i) {
				let array = new Array();
				for (let i = 0; i < this.imagePaths.length; i++) {
					array.push(this.imagePaths[i].path);
				}
				uni.previewImage({
					urls: array,
					current: i
				});
			},
			
			/**
			 * 删除图片点击事件
			 * @param {Object} i
			 */
			onImageDelTap: function(i) {
				let that = this;
				// 先判断当前图片是否存在 heiImageId 字段（仅在编辑模式的服务端图片有此字段）
				let imagePath = this.imagePaths[i];
				if (imagePath.heiImageId != undefined && imagePath.heiImageId != "") {
					// 直接移除服务端图片
					uni.showModal({
						title: "确定删除",
						content: "确定要删除这张图片吗，此操作会直接删除云端图片",
						success: function(res) {
							if (res.confirm) {
								deleteHeiImage(imagePath.heiImageId).then(data => {
									// 删除成功
									that.imagePaths.splice(i, 1);
								}).catch(err => {
									uni.showModal({
										title: "删除图片失败",
										content: err
									});
								});
							}
						}
					})
				} else {
					// 新增嘿文模式，是本地图片，直接删除数组变量中数据
					this.imagePaths.splice(i, 1);
				}
			},
			
			/**
			 * 嘿文编辑框行数变化事件
			 * @param {Object} res
			 */
			onContentLineChange: function(res) {
				let lineCount = res.detail.lineCount;
				if (lineCount >= 5) {
					// 嘿文内容行数到第 5 行时才开启自动高度
					this.contentAutoHeight = true;
				} else {
					this.contentAutoHeight = false;
				}
			}
		}
	}
</script>

<style lang="scss">
	.content {
		padding: 20rpx;
	}
	.input-title-view {
		background-color: white;
		padding: 20rpx;
		border-radius: 20px;
		padding-left: 30rpx;
		padding-right: 30rpx;
		margin-bottom: 30rpx;
	}
	
	.input-content-view {
		background-color: white;
		padding: 20rpx;
		padding-left: 10rpx;
		padding-right: 10rpx;
		border-radius: 20px;
		margin-bottom: 30rpx;
	}
	
	.images-view {
		background-color: white;
		padding: 30rpx;
		padding-left: 20rpx;
		padding-bottom: 20rpx;
		border-radius: 20px;
		margin-bottom: 40rpx;
	}
	
	.mimages-viwe {
		display: inline-block;
		vertical-align: top;
		position: relative;
		overflow: hidden;
		border-radius: 8px;
	}
	
	.mimage {
		width: 155rpx;
		height: 155rpx;
		// border: solid 1px $u-info-disabled;
		background-color: white;
		border-radius: 8px;
		margin-left: 10rpx;
	}
	
	.mimage-del {
		position: absolute;
		top: 0px;
		right: 0px;
		background-color: rgba(0, 0, 0, .5);
		width: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		border-radius: 0px 8px 0px 0px;
		color: white;
	}
	
	.image-add-view {
		width: 155rpx;
		height: 155rpx;
		line-height: 155rpx;
		display: inline-block;
		vertical-align: top;
		margin-left: 10rpx;
		border-radius: 8px;
		background-color: white;
		border: solid 1px $u-info-disabled;
		text-align: center;
	}
	
	.image-add {
		font-size: 54rpx;
	}
</style>
